diff --git a/sdk/search/azure-search-documents/assets.json b/sdk/search/azure-search-documents/assets.json index c43acc0bbf7d..c6ed4b633413 100644 --- a/sdk/search/azure-search-documents/assets.json +++ b/sdk/search/azure-search-documents/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "python", "TagPrefix": "python/search/azure-search-documents", - "Tag": "python/search/azure-search-documents_5fa507ca6f" + "Tag": "python/search/azure-search-documents_3ab3bb866c" } 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 index 63bbb287e1c8..d5a084e0fd25 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_api_versions.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_api_versions.py @@ -11,7 +11,7 @@ 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 diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/__init__.py index b24a07c02d65..53c089b12436 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/__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 SearchIndexClient # type: ignore +from ._version import VERSION + +__version__ = VERSION try: from ._patch import __all__ as _patch_all 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/_generated/_client.py similarity index 69% 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/_generated/_client.py index 122aa5e41f78..e0a7c8a49c14 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/_search_index_client.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/_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 ._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. + """SearchIndexClient. :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 = SearchIndexClientConfiguration( + 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/_generated/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/_configuration.py index 5ebd4a3efbe9..3a65dea8d7d0 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_generated/_configuration.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/_configuration.py @@ -1,14 +1,20 @@ # 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 typing import Any +from typing import Any, TYPE_CHECKING, Union +from azure.core.credentials import AzureKeyCredential from azure.core.pipeline import policies -VERSION = "unknown" +from ._version import VERSION + +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential class SearchIndexClientConfiguration: # pylint: disable=too-many-instance-attributes @@ -17,30 +23,48 @@ class SearchIndexClientConfiguration: # pylint: disable=too-many-instance-attri Note that all parameters used to create this instance are saved as instance attributes. - :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__(self, endpoint: str, index_name: str, **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2025-08-01-preview") + 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 - kwargs.setdefault("sdk_moniker", "searchindexclient/{}".format(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) @@ -51,3 +75,5 @@ def _configure(self, **kwargs: Any) -> None: 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/_utils/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/_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/_generated/_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/_generated/_utils/model_base.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/_utils/model_base.py new file mode 100644 index 000000000000..12926fa98dcf --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/_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/_generated/_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/_generated/_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/_generated/_utils/utils.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/_utils/utils.py new file mode 100644 index 000000000000..927adb7c8ae2 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/_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/_generated/_validation.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/_validation.py new file mode 100644 index 000000000000..f5af3a4eb8a2 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/_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/_generated/_version.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/_version.py new file mode 100644 index 000000000000..be71c81bd282 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/_version.py @@ -0,0 +1,9 @@ +# 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 = "1.0.0b1" 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 index b24a07c02d65..a5266d617dfe 100644 --- 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 @@ -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 ._search_index_client import SearchIndexClient # type: ignore +from ._client import SearchIndexClient # type: ignore try: from ._patch import __all__ as _patch_all 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/_generated/aio/_client.py similarity index 71% 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/_generated/aio/_client.py index 916d6e5380e5..f3e5fc0165de 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/_generated/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 .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. + """SearchIndexClient. :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 = SearchIndexClientConfiguration( + 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/_generated/aio/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/_configuration.py index ed4c0a0a8a8d..8cf24b8e2406 100644 --- 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 @@ -1,14 +1,20 @@ # 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 typing import Any +from typing import Any, TYPE_CHECKING, Union +from azure.core.credentials import AzureKeyCredential from azure.core.pipeline import policies -VERSION = "unknown" +from .._version import VERSION + +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential class SearchIndexClientConfiguration: # pylint: disable=too-many-instance-attributes @@ -17,30 +23,52 @@ class SearchIndexClientConfiguration: # pylint: disable=too-many-instance-attri Note that all parameters used to create this instance are saved as instance attributes. - :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__(self, endpoint: str, index_name: str, **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2025-08-01-preview") + 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 - kwargs.setdefault("sdk_moniker", "searchindexclient/{}".format(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) @@ -51,3 +79,5 @@ def _configure(self, **kwargs: Any) -> None: 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/aio/operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/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/_generated/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/_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/aio/operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/aio/operations/_operations.py new file mode 100644 index 000000000000..5cab9e143c53 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/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 SearchIndexClientConfiguration + +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.SearchIndexClient`'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: 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, *, 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/indexes/_generated/aio/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/__init__.py similarity index 68% rename from sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/__init__.py index 7b3c14c7b1b6..cf8730eed722 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/aio/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/__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_service_client import SearchServiceClient # type: ignore +from ._client import SearchServiceClient # type: ignore +from .._version import VERSION + +__version__ = VERSION try: from ._patch import __all__ as _patch_all 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/_generated/indexes/_client.py similarity index 65% 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/_generated/indexes/_client.py index 7fccc649dc7f..115b4205bb52 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/_generated/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 .._utils.serialization import Deserializer, Serializer from ._configuration import SearchServiceClientConfiguration -from ._utils.serialization import Deserializer, Serializer from .operations import ( + AgentsOperations, AliasesOperations, DataSourcesOperations, IndexersOperations, IndexesOperations, - KnowledgeAgentsOperations, - KnowledgeSourcesOperations, SkillsetsOperations, + SourcesOperations, SynonymMapsOperations, _SearchServiceClientOperationsMixin, ) +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 + """SearchServiceClient. + :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 = SearchServiceClientConfiguration(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/_generated/indexes/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/_configuration.py new file mode 100644 index 000000000000..1c82fb808886 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/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 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: 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/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/_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/_generated/indexes/_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/_generated/indexes/_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/_generated/indexes/_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/_generated/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/_generated/indexes/_utils/model_base.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/_utils/model_base.py new file mode 100644 index 000000000000..12926fa98dcf --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/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/agent/_generated/_utils/serialization.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/_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/_generated/indexes/_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/_generated/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/_generated/indexes/_utils/utils.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/_utils/utils.py new file mode 100644 index 000000000000..927adb7c8ae2 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/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/_generated/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/aio/__init__.py similarity index 72% rename from sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/aio/__init__.py index 7b3c14c7b1b6..731c020e69a8 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/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 ._search_service_client import SearchServiceClient # type: ignore +from ._client import SearchServiceClient # type: ignore try: from ._patch import __all__ as _patch_all 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/_generated/indexes/aio/_client.py similarity index 66% 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/_generated/indexes/aio/_client.py index d0f1b99796c9..79c02d7f20a6 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/_generated/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 ..._utils.serialization import Deserializer, Serializer from ._configuration import SearchServiceClientConfiguration from .operations import ( + AgentsOperations, AliasesOperations, DataSourcesOperations, IndexersOperations, IndexesOperations, - KnowledgeAgentsOperations, - KnowledgeSourcesOperations, SkillsetsOperations, + SourcesOperations, SynonymMapsOperations, _SearchServiceClientOperationsMixin, ) +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 + """SearchServiceClient. + :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 = SearchServiceClientConfiguration(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/_generated/indexes/aio/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/aio/_configuration.py new file mode 100644 index 000000000000..c8af5aea4697 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/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 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: 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/aio/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/aio/_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/_generated/indexes/aio/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/aio/operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/aio/operations/__init__.py new file mode 100644 index 000000000000..12192a4a4348 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/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 _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__ = [ + "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/_generated/indexes/aio/operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/aio/operations/_operations.py new file mode 100644 index 000000000000..35461865ddd3 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/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_service_get_index_stats_summary_request, + build_search_service_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 SearchServiceClientConfiguration + +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.SearchServiceClient`'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: 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, + 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.SearchServiceClient`'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: 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, **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.SearchServiceClient`'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: 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, + 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.SearchServiceClient`'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: 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, + 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.SearchServiceClient`'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: 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, + 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.SearchServiceClient`'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: 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, + 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.SearchServiceClient`'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: 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, + 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.SearchServiceClient`'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: 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, + 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 _SearchServiceClientOperationsMixin( + ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], SearchServiceClientConfiguration] +): + + @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_service_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_service_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/aio/operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/aio/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/_generated/indexes/aio/operations/_patch.py 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/_generated/indexes/models/__init__.py similarity index 93% rename from sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/models/__init__.py index a376f02c866a..aa58ae78fc31 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/indexes/_generated/models/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/models/__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 @@ -11,7 +13,7 @@ from ._patch import * # pylint: disable=unused-wildcard-import -from ._models_py3 import ( # type: ignore +from ._models import ( # type: ignore AIServicesAccountIdentity, AIServicesAccountKey, AIServicesVisionParameters, @@ -30,12 +32,14 @@ AzureOpenAITokenizerParameters, AzureOpenAIVectorizer, AzureOpenAIVectorizerParameters, + AzureOpenAiParameters, BM25SimilarityAlgorithm, BinaryQuantizationCompression, CharFilter, + ChatCompletionCommonModelParameters, ChatCompletionResponseFormat, - ChatCompletionResponseFormatJsonSchemaProperties, ChatCompletionSchema, + ChatCompletionSchemaProperties, ChatCompletionSkill, CjkBigramTokenFilter, ClassicSimilarityAlgorithm, @@ -43,9 +47,9 @@ CognitiveServicesAccount, CognitiveServicesAccountKey, CommonGramTokenFilter, - CommonModelParameters, ConditionalSkill, CorsOptions, + CreatedResources, CustomAnalyzer, CustomEntity, CustomEntityAlias, @@ -63,15 +67,11 @@ DocumentIntelligenceLayoutSkillChunkingProperties, DocumentKeysOrIds, EdgeNGramTokenFilter, - EdgeNGramTokenFilterV2, EdgeNGramTokenizer, ElisionTokenFilter, EntityLinkingSkill, EntityRecognitionSkill, EntityRecognitionSkillV3, - ErrorAdditionalInfo, - ErrorDetail, - ErrorResponse, ExhaustiveKnnAlgorithmConfiguration, ExhaustiveKnnParameters, FieldMapping, @@ -95,9 +95,8 @@ KeyPhraseExtractionSkill, KeywordMarkerTokenFilter, KeywordTokenizer, - KeywordTokenizerV2, KnowledgeAgent, - KnowledgeAgentAzureOpenAIModel, + KnowledgeAgentAzureOpenAiModel, KnowledgeAgentModel, KnowledgeAgentOutputConfiguration, KnowledgeAgentRequestLimits, @@ -109,18 +108,14 @@ LexicalNormalizer, LexicalTokenizer, LimitTokenFilter, - ListAliasesResult, ListDataSourcesResult, - ListIndexStatsSummary, ListIndexersResult, - ListIndexesResult, ListKnowledgeAgentsResult, ListKnowledgeSourcesResult, ListSkillsetsResult, ListSynonymMapsResult, LuceneStandardAnalyzer, LuceneStandardTokenizer, - LuceneStandardTokenizerV2, MagnitudeScoringFunction, MagnitudeScoringParameters, MappingCharFilter, @@ -128,20 +123,18 @@ MicrosoftLanguageStemmingTokenizer, MicrosoftLanguageTokenizer, NGramTokenFilter, - NGramTokenFilterV2, NGramTokenizer, NativeBlobSoftDeleteDeletionDetectionPolicy, OcrSkill, OutputFieldMappingEntry, PIIDetectionSkill, - PathHierarchyTokenizerV2, + PathHierarchyTokenizer, PatternAnalyzer, PatternCaptureTokenFilter, PatternReplaceCharFilter, PatternReplaceTokenFilter, PatternTokenizer, PhoneticTokenFilter, - RequestOptions, RescoringOptions, ResourceCounter, ScalarQuantizationCompression, @@ -216,13 +209,14 @@ VectorSearchProfile, VectorSearchVectorizer, VisionVectorizeSkill, + WebApiHttpHeaders, WebApiSkill, WebApiVectorizer, WebApiVectorizerParameters, WordDelimiterTokenFilter, ) -from ._search_service_client_enums import ( # type: ignore +from ._enums import ( # type: ignore AIFoundryModelCatalogName, AzureOpenAIModelName, BlobIndexerDataToExtract, @@ -242,7 +236,6 @@ EdgeNGramTokenFilterSide, EntityCategory, EntityRecognitionSkillLanguage, - Enum0, ImageAnalysisSkillLanguage, ImageDetail, IndexProjectionMode, @@ -319,12 +312,14 @@ "AzureOpenAITokenizerParameters", "AzureOpenAIVectorizer", "AzureOpenAIVectorizerParameters", + "AzureOpenAiParameters", "BM25SimilarityAlgorithm", "BinaryQuantizationCompression", "CharFilter", + "ChatCompletionCommonModelParameters", "ChatCompletionResponseFormat", - "ChatCompletionResponseFormatJsonSchemaProperties", "ChatCompletionSchema", + "ChatCompletionSchemaProperties", "ChatCompletionSkill", "CjkBigramTokenFilter", "ClassicSimilarityAlgorithm", @@ -332,9 +327,9 @@ "CognitiveServicesAccount", "CognitiveServicesAccountKey", "CommonGramTokenFilter", - "CommonModelParameters", "ConditionalSkill", "CorsOptions", + "CreatedResources", "CustomAnalyzer", "CustomEntity", "CustomEntityAlias", @@ -352,15 +347,11 @@ "DocumentIntelligenceLayoutSkillChunkingProperties", "DocumentKeysOrIds", "EdgeNGramTokenFilter", - "EdgeNGramTokenFilterV2", "EdgeNGramTokenizer", "ElisionTokenFilter", "EntityLinkingSkill", "EntityRecognitionSkill", "EntityRecognitionSkillV3", - "ErrorAdditionalInfo", - "ErrorDetail", - "ErrorResponse", "ExhaustiveKnnAlgorithmConfiguration", "ExhaustiveKnnParameters", "FieldMapping", @@ -384,9 +375,8 @@ "KeyPhraseExtractionSkill", "KeywordMarkerTokenFilter", "KeywordTokenizer", - "KeywordTokenizerV2", "KnowledgeAgent", - "KnowledgeAgentAzureOpenAIModel", + "KnowledgeAgentAzureOpenAiModel", "KnowledgeAgentModel", "KnowledgeAgentOutputConfiguration", "KnowledgeAgentRequestLimits", @@ -398,18 +388,14 @@ "LexicalNormalizer", "LexicalTokenizer", "LimitTokenFilter", - "ListAliasesResult", "ListDataSourcesResult", - "ListIndexStatsSummary", "ListIndexersResult", - "ListIndexesResult", "ListKnowledgeAgentsResult", "ListKnowledgeSourcesResult", "ListSkillsetsResult", "ListSynonymMapsResult", "LuceneStandardAnalyzer", "LuceneStandardTokenizer", - "LuceneStandardTokenizerV2", "MagnitudeScoringFunction", "MagnitudeScoringParameters", "MappingCharFilter", @@ -417,20 +403,18 @@ "MicrosoftLanguageStemmingTokenizer", "MicrosoftLanguageTokenizer", "NGramTokenFilter", - "NGramTokenFilterV2", "NGramTokenizer", "NativeBlobSoftDeleteDeletionDetectionPolicy", "OcrSkill", "OutputFieldMappingEntry", "PIIDetectionSkill", - "PathHierarchyTokenizerV2", + "PathHierarchyTokenizer", "PatternAnalyzer", "PatternCaptureTokenFilter", "PatternReplaceCharFilter", "PatternReplaceTokenFilter", "PatternTokenizer", "PhoneticTokenFilter", - "RequestOptions", "RescoringOptions", "ResourceCounter", "ScalarQuantizationCompression", @@ -505,6 +489,7 @@ "VectorSearchProfile", "VectorSearchVectorizer", "VisionVectorizeSkill", + "WebApiHttpHeaders", "WebApiSkill", "WebApiVectorizer", "WebApiVectorizerParameters", @@ -528,7 +513,6 @@ "EdgeNGramTokenFilterSide", "EntityCategory", "EntityRecognitionSkillLanguage", - "Enum0", "ImageAnalysisSkillLanguage", "ImageDetail", "IndexProjectionMode", 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/_generated/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/_generated/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/_generated/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/_generated/indexes/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/models/_models.py new file mode 100644 index 000000000000..4cef621fc010 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/models/_models.py @@ -0,0 +1,11731 @@ +# 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 + +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, +) + +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 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 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.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, + 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 + + +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 '#'. + :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 + :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 '#'. + :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 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, + *, + 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] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.odata_type = "#Microsoft.Skills.Custom.WebApiSkill" # type: ignore + + +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 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, + *, + vectorizer_name: str, + web_api_parameters: Optional["_models.WebApiVectorizerParameters"] = 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.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 + """ + + 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, + *, + 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, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +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 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, + 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/models/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/models/_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/_generated/indexes/models/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/operations/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/operations/__init__.py new file mode 100644 index 000000000000..12192a4a4348 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/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 _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__ = [ + "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/_generated/indexes/operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/operations/_operations.py new file mode 100644 index 000000000000..3428862ea026 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/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 SearchServiceClientConfiguration + +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_service_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_service_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.SearchServiceClient`'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: 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, + 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.SearchServiceClient`'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: 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(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.SearchServiceClient`'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: 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, + 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.SearchServiceClient`'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: 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, + 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.SearchServiceClient`'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: 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, + 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.SearchServiceClient`'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: 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, + 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.SearchServiceClient`'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: 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, + 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.SearchServiceClient`'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: 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, + 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 _SearchServiceClientOperationsMixin( + ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], SearchServiceClientConfiguration] +): + + @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_service_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_service_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/operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/indexes/operations/_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/_generated/indexes/operations/_patch.py 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/_generated/knowledgebase/__init__.py similarity index 65% rename from sdk/search/azure-search-documents/azure/search/documents/agent/_generated/aio/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/_generated/knowledgebase/__init__.py index 79e8ad096465..f721cfb1ed80 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/agent/_generated/aio/__init__.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/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 ._knowledge_agent_retrieval_client import KnowledgeAgentRetrievalClient # 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__ = [ - "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/_knowledge_agent_retrieval_client.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/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/_generated/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/_generated/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/_generated/knowledgebase/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/knowledgebase/_configuration.py new file mode 100644 index 000000000000..425408a1c073 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/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/indexes/_generated/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/knowledgebase/_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/_generated/knowledgebase/_patch.py 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/_generated/knowledgebase/_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/_generated/knowledgebase/_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/_generated/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/_generated/knowledgebase/_utils/model_base.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/knowledgebase/_utils/model_base.py new file mode 100644 index 000000000000..12926fa98dcf --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/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/indexes/_generated/_utils/serialization.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/knowledgebase/_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/_generated/knowledgebase/_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/_generated/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/_generated/knowledgebase/_utils/utils.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/knowledgebase/_utils/utils.py new file mode 100644 index 000000000000..927adb7c8ae2 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/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/_generated/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/_generated/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/_generated/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/_generated/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/_generated/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/_generated/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/_generated/knowledgebase/aio/_configuration.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/knowledgebase/aio/_configuration.py new file mode 100644 index 000000000000..ec28807286a4 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/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/indexes/_generated/aio/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/knowledgebase/aio/_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/_generated/knowledgebase/aio/_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/_generated/knowledgebase/aio/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/_generated/knowledgebase/aio/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/_generated/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/_generated/knowledgebase/aio/operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/knowledgebase/aio/operations/_operations.py new file mode 100644 index 000000000000..e0ff63ac5b1e --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/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/aio/operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/knowledgebase/aio/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/_generated/knowledgebase/aio/operations/_patch.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/_generated/knowledgebase/models/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/knowledgebase/models/__init__.py new file mode 100644 index 000000000000..f800324958aa --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/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/_generated/knowledgebase/models/_enums.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/knowledgebase/models/_enums.py new file mode 100644 index 000000000000..31ccafa2e2fb --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/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/_generated/knowledgebase/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/knowledgebase/models/_models.py new file mode 100644 index 000000000000..52e7361e8888 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/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/models/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/knowledgebase/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/_generated/knowledgebase/models/_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/_generated/knowledgebase/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/_generated/knowledgebase/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/_generated/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/_generated/knowledgebase/operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/knowledgebase/operations/_operations.py new file mode 100644 index 000000000000..f353833f4cb9 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/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/operations/_patch.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/knowledgebase/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/_generated/knowledgebase/operations/_patch.py 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 index 061cb503b94a..86d9675d77ac 100644 --- 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 @@ -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 @@ -11,9 +13,8 @@ from ._patch import * # pylint: disable=unused-wildcard-import -from ._models_py3 import ( # type: ignore +from ._models import ( # type: ignore AutocompleteItem, - AutocompleteOptions, AutocompleteRequest, AutocompleteResult, DebugInfo, @@ -27,6 +28,7 @@ IndexBatch, IndexDocumentsResult, IndexingResult, + LookupDocument, QueryAnswerResult, QueryCaptionResult, QueryResultDocumentInnerHit, @@ -35,16 +37,13 @@ QueryResultDocumentSubscores, QueryRewritesDebugInfo, QueryRewritesValuesDebugInfo, - RequestOptions, SearchDocumentsResult, - SearchOptions, SearchRequest, SearchResult, SearchScoreThreshold, SemanticDebugInfo, SingleVectorFieldResult, SuggestDocumentsResult, - SuggestOptions, SuggestRequest, SuggestResult, TextResult, @@ -58,7 +57,7 @@ VectorsDebugInfo, ) -from ._search_index_client_enums import ( # type: ignore +from ._enums import ( # type: ignore AutocompleteMode, HybridCountAndFacetMode, IndexActionType, @@ -86,7 +85,6 @@ __all__ = [ "AutocompleteItem", - "AutocompleteOptions", "AutocompleteRequest", "AutocompleteResult", "DebugInfo", @@ -100,6 +98,7 @@ "IndexBatch", "IndexDocumentsResult", "IndexingResult", + "LookupDocument", "QueryAnswerResult", "QueryCaptionResult", "QueryResultDocumentInnerHit", @@ -108,16 +107,13 @@ "QueryResultDocumentSubscores", "QueryRewritesDebugInfo", "QueryRewritesValuesDebugInfo", - "RequestOptions", "SearchDocumentsResult", - "SearchOptions", "SearchRequest", "SearchResult", "SearchScoreThreshold", "SemanticDebugInfo", "SingleVectorFieldResult", "SuggestDocumentsResult", - "SuggestOptions", "SuggestRequest", "SuggestResult", "TextResult", 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/_generated/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/_generated/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/_generated/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/_generated/models/_models.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/models/_models.py new file mode 100644 index 000000000000..fda9f9667a56 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/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/_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/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/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/_generated/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/_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/operations/_operations.py b/sdk/search/azure-search-documents/azure/search/documents/_generated/operations/_operations.py new file mode 100644 index 000000000000..f82f1af6a168 --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/_generated/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 SearchIndexClientConfiguration +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.SearchIndexClient`'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: 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, *, 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/_index_documents_batch.py b/sdk/search/azure-search-documents/azure/search/documents/_index_documents_batch.py index db107813fd63..8e8b1b236177 100644 --- 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 @@ -139,7 +139,15 @@ def enqueue_actions(self, new_actions: Union[IndexAction, List[IndexAction]], ** 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] + new_actions: List[IndexAction] = [] + for document in documents: + index_action = IndexAction(action_type=action_type) + if isinstance(document, dict): + for key, value in document.items(): + index_action[key] = value + else: + index_action[""] = document + new_actions.append(index_action) 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 index de431227e160..cfa31fcf3834 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_paging.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_paging.py @@ -15,7 +15,7 @@ def convert_search_result(result): - ret = result.additional_properties + ret = result ret["@search.score"] = result.score ret["@search.reranker_score"] = result.reranker_score ret["@search.highlights"] = result.highlights @@ -30,7 +30,7 @@ def pack_continuation_token(response, api_version=DEFAULT_VERSION): token = { "apiVersion": api_version, "nextLink": response.next_link, - "nextPageParameters": response.next_page_parameters.serialize(), + "nextPageParameters": json.dumps(response.next_page_parameters), } return base64.b64encode(json.dumps(token).encode("utf-8")) return None @@ -40,7 +40,8 @@ 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) + obj_dict = json.loads(next_page_parameters) + next_page_request = SearchRequest(obj_dict) return next_link, next_page_request 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 index 432df9673d5b..6e6f38b4b914 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_search_client.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_search_client.py @@ -3,7 +3,7 @@ # 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 typing import cast, List, Any, Union, Dict, Optional from azure.core.rest import HttpRequest, HttpResponse from azure.core.credentials import AzureKeyCredential, TokenCredential @@ -11,8 +11,10 @@ from ._api_versions import DEFAULT_VERSION from ._generated import SearchIndexClient from ._generated.models import ( + AutocompleteItem, AutocompleteMode, AutocompleteRequest, + HybridSearch, IndexAction, IndexBatch, IndexingResult, @@ -29,14 +31,14 @@ QueryDebugMode, QueryRewritesType, SuggestRequest, - HybridSearch, + SuggestResult, ) 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 ._utils import DEFAULT_AUDIENCE, get_answer_query, get_rewrites_query from ._version import SDK_MONIKER @@ -74,27 +76,21 @@ def __init__( 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 - ) + self._audience = kwargs.pop("audience", None) + if not self._audience: + self._audience = DEFAULT_AUDIENCE + scope = self._audience.rstrip("/") + "/.default" + credential_scopes = [scope] + self._aad = not isinstance(credential, AzureKeyCredential) + self._client = SearchIndexClient( + endpoint=endpoint, + credential=credential, + index_name=index_name, + sdk_moniker=SDK_MONIKER, + api_version=self._api_version, + credential_scopes=credential_scopes, + **kwargs + ) def __repr__(self) -> str: return "".format(repr(self._endpoint), repr(self._index_name))[:1024] @@ -182,7 +178,7 @@ def search( 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, + query_source_authorization: Optional[str] = None, **kwargs: Any ) -> SearchItemPaged[Dict]: # pylint:disable=too-many-locals, disable=redefined-builtin @@ -310,10 +306,10 @@ def search( :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 + :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 x_ms_query_source_authorization: str + :paramtype query_source_authorization: str :return: List of search results. :rtype: SearchItemPaged[dict] @@ -402,7 +398,7 @@ def search( 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["query_source_authorization"] = query_source_authorization kwargs["api_version"] = self._api_version return SearchItemPaged(self._client, query, kwargs, page_iterator_class=SearchPageIterator) @@ -422,7 +418,7 @@ def suggest( select: Optional[List[str]] = None, top: Optional[int] = None, **kwargs - ) -> List[MutableMapping[str, Any]]: + ) -> List[SuggestResult]: """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 @@ -457,7 +453,7 @@ def suggest( 100. The default is 5. :return: List of suggestion results. - :rtype: list[dict] + :rtype: list[~azure.search.documents.models.SuggestResult] .. admonition:: Example: @@ -491,7 +487,7 @@ def suggest( 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] + results = response.results return results @distributed_trace @@ -509,7 +505,7 @@ def autocomplete( search_fields: Optional[List[str]] = None, top: Optional[int] = None, **kwargs - ) -> List[MutableMapping[str, Any]]: + ) -> List[AutocompleteItem]: """Get search auto-completion results from the Azure search index. :param str search_text: The search text on which to base autocomplete results. @@ -539,7 +535,7 @@ def autocomplete( :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] + :rtype: list[~azure.search.documents.models.AutocompleteItem] .. admonition:: Example: @@ -570,7 +566,7 @@ def autocomplete( 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] + results = response.results return results # pylint:disable=client-method-missing-tracing-decorator @@ -743,4 +739,4 @@ def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs) :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 + 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_indexing_buffered_sender.py b/sdk/search/azure-search-documents/azure/search/documents/_search_indexing_buffered_sender.py index 394a3660bb53..f4e503395439 100644 --- 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 @@ -10,7 +10,7 @@ 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 ._utils import is_retryable_status_code, DEFAULT_AUDIENCE from .indexes import SearchIndexClient as SearchServiceClient from ._search_indexing_buffered_sender_base import SearchIndexingBufferedSenderBase from ._generated import SearchIndexClient @@ -61,27 +61,21 @@ def __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._audience = kwargs.pop("audience", None) + if not self._audience: + self._audience = DEFAULT_AUDIENCE + scope = self._audience.rstrip("/") + "/.default" + credential_scopes = [scope] + self._aad = not isinstance(credential, AzureKeyCredential) + self._client = SearchIndexClient( + endpoint=endpoint, + credential=credential, + index_name=index_name, + sdk_moniker=SDK_MONIKER, + api_version=self._api_version, + credential_scopes=credential_scopes, + **kwargs + ) self._reset_timer() def _cleanup(self, flush: bool = True) -> None: @@ -167,11 +161,7 @@ def _process(self, timeout: int = 86400, **kwargs) -> bool: 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 - ) + action = next(x for x in actions if x and str(x.get(self._index_key)) == result.key) if result.succeeded: self._callback_succeed(action) elif is_retryable_status_code(result.status_code): @@ -328,7 +318,7 @@ 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 "") + key = cast(str, action.get(self._index_key) if action else "") counter = self._retry_counter.get(key) if not counter: # first time that fails diff --git a/sdk/search/azure-search-documents/azure/search/documents/_utils.py b/sdk/search/azure-search-documents/azure/search/documents/_utils.py index 5b912120c1ed..ffefe0a505ec 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/_utils.py +++ b/sdk/search/azure-search-documents/azure/search/documents/_utils.py @@ -4,10 +4,6 @@ # 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" @@ -44,16 +40,6 @@ def is_retryable_status_code(status_code: Optional[int]) -> bool: 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. 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/_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/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/_index_documents_batch_async.py b/sdk/search/azure-search-documents/azure/search/documents/aio/_index_documents_batch_async.py index 74f8d88c8b18..5a5bbfdaeb11 100644 --- 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 @@ -133,7 +133,15 @@ async def enqueue_actions(self, new_actions: Union[IndexAction, List[IndexAction 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] + new_actions: List[IndexAction] = [] + for document in documents: + index_action = IndexAction(action_type=action_type) + if isinstance(document, dict): + for key, value in document.items(): + index_action[key] = value + else: + index_action[""] = document + new_actions.append(index_action) async with self._lock: self._actions.extend(new_actions) return new_actions 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 index 01a9541ae995..0665c70c6667 100644 --- 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 @@ -3,18 +3,20 @@ # 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 typing import cast, List, Union, Any, Optional, Dict 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 .._utils import DEFAULT_AUDIENCE, get_answer_query, get_rewrites_query from .._generated.aio import SearchIndexClient from .._generated.models import ( + AutocompleteItem, AutocompleteMode, AutocompleteRequest, + HybridSearch, IndexAction, IndexBatch, IndexingResult, @@ -31,7 +33,7 @@ QueryRewritesType, QueryDebugMode, SuggestRequest, - HybridSearch, + SuggestResult, ) from .._search_documents_error import RequestEntityTooLargeError from .._index_documents_batch import IndexDocumentsBatch @@ -76,27 +78,21 @@ def __init__( 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 - ) + self._audience = kwargs.pop("audience", None) + if not self._audience: + self._audience = DEFAULT_AUDIENCE + scope = self._audience.rstrip("/") + "/.default" + credential_scopes = [scope] + self._aad = not isinstance(credential, AzureKeyCredential) + self._client = SearchIndexClient( + endpoint=endpoint, + credential=credential, + index_name=index_name, + sdk_moniker=SDK_MONIKER, + api_version=self._api_version, + credential_scopes=credential_scopes, + **kwargs + ) def __repr__(self) -> str: return "".format(repr(self._endpoint), repr(self._index_name))[:1024] @@ -420,7 +416,7 @@ async def suggest( select: Optional[List[str]] = None, top: Optional[int] = None, **kwargs - ) -> List[MutableMapping[str, Any]]: + ) -> List[SuggestResult]: """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 @@ -454,7 +450,7 @@ async def suggest( :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] + :rtype: list[~azure.search.documents.models.SuggestResult] .. admonition:: Example: @@ -488,7 +484,7 @@ async def suggest( 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] + results = response.results return results @distributed_trace_async @@ -506,7 +502,7 @@ async def autocomplete( search_fields: Optional[List[str]] = None, top: Optional[int] = None, **kwargs - ) -> List[MutableMapping[str, Any]]: + ) -> List[AutocompleteItem]: """Get search auto-completion results from the Azure search index. :param str search_text: The search text on which to base autocomplete results. @@ -536,7 +532,7 @@ async def autocomplete( :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] + :rtype: list[~azure.search.documents.models.AutocompleteItem] .. admonition:: Example: @@ -545,7 +541,7 @@ async def autocomplete( :end-before: [END autocomplete_query_async] :language: python :dedent: 4 - :caption: Get a auto-completions. + :caption: Get an auto-completions. """ autocomplete_mode = mode filter_arg = filter @@ -567,7 +563,7 @@ async def autocomplete( 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] + results = response.results return results # pylint:disable=client-method-missing-tracing-decorator-async @@ -740,4 +736,4 @@ async def send_request(self, request: HttpRequest, *, stream: bool = False, **kw :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 + 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 index 9990a7dca659..af7b422d29e4 100644 --- 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 @@ -11,7 +11,7 @@ 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 .._utils import is_retryable_status_code, DEFAULT_AUDIENCE from .._search_indexing_buffered_sender_base import SearchIndexingBufferedSenderBase from .._generated.aio import SearchIndexClient from .._generated.models import IndexingResult, IndexBatch, IndexAction @@ -60,27 +60,21 @@ def __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._audience = kwargs.pop("audience", None) + if not self._audience: + self._audience = DEFAULT_AUDIENCE + scope = self._audience.rstrip("/") + "/.default" + credential_scopes = [scope] + self._aad = not isinstance(credential, AzureKeyCredential) + self._client = SearchIndexClient( + endpoint=endpoint, + credential=credential, + index_name=index_name, + sdk_moniker=SDK_MONIKER, + api_version=self._api_version, + credential_scopes=credential_scopes, + **kwargs + ) self._reset_timer() async def _cleanup(self, flush: bool = True) -> None: @@ -169,11 +163,7 @@ async def _process(self, timeout: int = 86400, **kwargs) -> bool: 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 - ) + action = next(x for x in actions if x and str(x.get(self._index_key)) == result.key) if result.succeeded: await self._callback_succeed(action) elif is_retryable_status_code(result.status_code): @@ -331,7 +321,7 @@ 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 "") + key = cast(str, action.get(self._index_key) if action else "") counter = self._retry_counter.get(key) if not counter: # first time that fails 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/_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/_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/indexes/_search_index_client.py b/sdk/search/azure-search-documents/azure/search/documents/indexes/_search_index_client.py index 8d622df44258..6af78c39b8eb 100644 --- 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 @@ -12,13 +12,10 @@ 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 .._generated.indexes import SearchServiceClient as _SearchServiceClient +from ._utils import normalize_endpoint from .._headers_mixin import HeadersMixin -from .._utils import get_authentication_policy +from .._utils import DEFAULT_AUDIENCE from .._version import SDK_MONIKER from .._search_client import SearchClient from .models import ( @@ -54,21 +51,19 @@ def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, TokenCre 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 - ) + if not self._audience: + self._audience = DEFAULT_AUDIENCE + scope = self._audience.rstrip("/") + "/.default" + credential_scopes = [scope] + self._aad = not isinstance(credential, AzureKeyCredential) + self._client = _SearchServiceClient( + endpoint=endpoint, + credential=credential, + sdk_moniker=SDK_MONIKER, + api_version=self._api_version, + credential_scopes=credential_scopes, + **kwargs + ) def __enter__(self): self._client.__enter__() @@ -174,7 +169,7 @@ def get_index_statistics(self, index_name: str, **kwargs: Any) -> MutableMapping """ kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) result = self._client.indexes.get_statistics(index_name, **kwargs) - return result.as_dict() + return result @distributed_trace def delete_index( @@ -203,13 +198,13 @@ def delete_index( :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 + etag = index.e_tag # type: ignore except AttributeError: index_name = index - self._client.indexes.delete(index_name=index_name, error_map=error_map, **kwargs) + etag = None + self._client.indexes.delete(index_name=index_name, match_condition=match_condition, etag=etag, **kwargs) @distributed_trace def create_index(self, index: SearchIndex, **kwargs: Any) -> SearchIndex: @@ -274,15 +269,14 @@ def create_or_update_index( :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, + match_condition=match_condition, + etag=index.e_tag, **kwargs ) return cast(SearchIndex, SearchIndex._from_generated(result)) # pylint:disable=protected-access @@ -310,9 +304,7 @@ def analyze_text(self, index_name: str, analyze_request: AnalyzeTextOptions, **k """ 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 + index_name=index_name, request=analyze_request._to_generated(), **kwargs # pylint:disable=protected-access ) return result @@ -412,13 +404,15 @@ def delete_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) + if isinstance(synonym_map, str) and match_condition is not MatchConditions.Unconditionally: + raise ValueError("A model must be passed to use access conditions") try: name = synonym_map.name # type: ignore + etag = synonym_map.e_tag # type: ignore except AttributeError: name = synonym_map - self._client.synonym_maps.delete(synonym_map_name=name, error_map=error_map, **kwargs) + etag = None + self._client.synonym_maps.delete(synonym_map_name=name, match_condition=match_condition, etag=etag, **kwargs) @distributed_trace def create_synonym_map(self, synonym_map: SynonymMap, **kwargs: Any) -> SynonymMap: @@ -464,14 +458,13 @@ def create_or_update_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) 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, + match_condition=match_condition, prefer="return=representation", - error_map=error_map, + etag=synonym_map.e_tag, **kwargs ) return cast(SynonymMap, SynonymMap._from_generated(result)) # pylint:disable=protected-access @@ -485,7 +478,7 @@ def get_service_statistics(self, **kwargs: Any) -> MutableMapping[str, Any]: """ kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) result = self._client.get_service_statistics(**kwargs) - return result.as_dict() + return result @distributed_trace def list_index_stats_summary(self, **kwargs: Any) -> ItemPaged[IndexStatisticsSummary]: @@ -543,7 +536,7 @@ def get_alias(self, name: str, **kwargs: Any) -> SearchAlias: """ kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) result = self._client.aliases.get(name, **kwargs) - return result + return cast(SearchAlias, result) @distributed_trace def delete_alias( @@ -572,13 +565,15 @@ def delete_alias( :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) + if isinstance(alias, str) and match_condition is not MatchConditions.Unconditionally: + raise ValueError("A model must be passed to use access conditions") try: alias_name = alias.name # type: ignore + etag = alias.e_tag # type: ignore except AttributeError: alias_name = alias - self._client.aliases.delete(alias_name=alias_name, error_map=error_map, **kwargs) + etag = None + self._client.aliases.delete(alias_name=alias_name, match_condition=match_condition, etag=etag, **kwargs) @distributed_trace def create_alias(self, alias: SearchAlias, **kwargs: Any) -> SearchAlias: @@ -601,7 +596,7 @@ def create_alias(self, alias: SearchAlias, **kwargs: Any) -> SearchAlias: """ kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) result = self._client.aliases.create(alias, **kwargs) - return result # pylint:disable=protected-access + return cast(SearchAlias, result) @distributed_trace def create_or_update_alias( @@ -632,12 +627,15 @@ def create_or_update_alias( :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 + alias_name=alias.name, + alias=alias, + match_condition=match_condition, + prefer="return=representation", + etag=alias.e_tag, + **kwargs ) - return result # pylint:disable=protected-access + return cast(SearchAlias, result) @distributed_trace def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs) -> HttpResponse: @@ -650,7 +648,7 @@ def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs) :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 + return self._client.send_request(request, stream=stream, **kwargs) # pylint:disable=protected-access @distributed_trace def delete_agent( @@ -669,13 +667,13 @@ def delete_agent( :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 + etag = agent.e_tag # type: ignore except AttributeError: agent_name = agent - self._client.knowledge_agents.delete(agent_name=agent_name, error_map=error_map, **kwargs) + etag = None + self._client.agents.delete(agent_name=agent_name, match_condition=match_condition, etag=etag, **kwargs) @distributed_trace def create_agent(self, agent: KnowledgeAgent, **kwargs: Any) -> KnowledgeAgent: @@ -688,7 +686,7 @@ def create_agent(self, agent: KnowledgeAgent, **kwargs: Any) -> 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) + result = self._client.agents.create(agent, **kwargs) return result @distributed_trace @@ -714,10 +712,13 @@ def create_or_update_agent( :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 + result = self._client.agents.create_or_update( + agent_name=agent.name, + knowledge_agent=agent, + match_condition=match_condition, + prefer="return=representation", + etag=agent.e_tag, + **kwargs ) return result @@ -732,8 +733,8 @@ def get_agent(self, name: str, **kwargs: Any) -> 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 + result = self._client.agents.get(name, **kwargs) + return cast(KnowledgeAgent, result) @distributed_trace def list_agents(self, **kwargs: Any) -> ItemPaged[KnowledgeAgent]: @@ -745,7 +746,7 @@ def list_agents(self, **kwargs: Any) -> ItemPaged[KnowledgeAgent]: """ kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) # pylint:disable=protected-access - return cast(ItemPaged[KnowledgeAgent], self._client.knowledge_agents.list(**kwargs)) + return cast(ItemPaged[KnowledgeAgent], self._client.agents.list(**kwargs)) @distributed_trace def delete_knowledge_source( @@ -764,13 +765,13 @@ def delete_knowledge_source( :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 + etag = knowledge_source.e_tag # type: ignore except AttributeError: source_name = knowledge_source - self._client.knowledge_sources.delete(source_name=source_name, error_map=error_map, **kwargs) + etag = None + self._client.sources.delete(source_name=source_name, match_condition=match_condition, etag=etag, **kwargs) @distributed_trace def create_knowledge_source(self, knowledge_source: KnowledgeSource, **kwargs: Any) -> KnowledgeSource: @@ -783,7 +784,7 @@ def create_knowledge_source(self, knowledge_source: KnowledgeSource, **kwargs: A :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) + result = self._client.sources.create(knowledge_source, **kwargs) return result @distributed_trace @@ -809,13 +810,12 @@ def create_or_update_knowledge_source( :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( + result = self._client.sources.create_or_update( source_name=knowledge_source.name, knowledge_source=knowledge_source, + match_condition=match_condition, prefer="return=representation", - error_map=error_map, + etag=knowledge_source.e_tag, **kwargs ) return result @@ -831,8 +831,8 @@ def get_knowledge_source(self, name: str, **kwargs: Any) -> 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 + result = self._client.sources.get(name, **kwargs) + return cast(KnowledgeSource, result) @distributed_trace def list_knowledge_sources(self, **kwargs: Any) -> ItemPaged[KnowledgeSource]: @@ -844,4 +844,4 @@ def list_knowledge_sources(self, **kwargs: Any) -> ItemPaged[KnowledgeSource]: """ kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) # pylint:disable=protected-access - return cast(ItemPaged[KnowledgeSource], self._client.knowledge_sources.list(**kwargs)) + return cast(ItemPaged[KnowledgeSource], self._client.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 index b41006ac5158..39fe2a6fc53e 100644 --- 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 @@ -9,18 +9,15 @@ 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 ( +from .._generated.indexes import SearchServiceClient as _SearchServiceClient +from .._generated.indexes.models import ( SkillNames, SearchIndexerStatus, DocumentKeysOrIds, IndexerResyncOption, IndexerResyncBody, ) -from ._utils import ( - get_access_conditions, - normalize_endpoint, -) +from ._utils import normalize_endpoint from .models import ( SearchIndexer, SearchIndexerSkillset, @@ -30,7 +27,7 @@ ) from .._api_versions import DEFAULT_VERSION from .._headers_mixin import HeadersMixin -from .._utils import get_authentication_policy +from .._utils import DEFAULT_AUDIENCE from .._version import SDK_MONIKER @@ -54,22 +51,20 @@ def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, TokenCre 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 - ) + self._audience = kwargs.pop("audience", None) + if not self._audience: + self._audience = DEFAULT_AUDIENCE + scope = self._audience.rstrip("/") + "/.default" + credential_scopes = [scope] + self._aad = not isinstance(credential, AzureKeyCredential) + self._client = _SearchServiceClient( + endpoint=endpoint, + credential=credential, + sdk_moniker=SDK_MONIKER, + api_version=self._api_version, + credential_scopes=credential_scopes, + **kwargs + ) def __enter__(self) -> "SearchIndexerClient": self._client.__enter__() @@ -134,15 +129,14 @@ def create_or_update_indexer( :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, + match_condition=match_condition, prefer="return=representation", - error_map=error_map, + 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 @@ -247,13 +241,15 @@ def delete_indexer( :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) + if isinstance(indexer, str) and match_condition is not MatchConditions.Unconditionally: + raise ValueError("A model must be passed to use access conditions") try: name = indexer.name # type: ignore + etag = indexer.e_tag # type: ignore except AttributeError: name = indexer - self._client.indexers.delete(name, error_map=error_map, **kwargs) + etag = None + self._client.indexers.delete(name, match_condition=match_condition, etag=etag, **kwargs) @distributed_trace def run_indexer(self, name: str, **kwargs: Any) -> None: @@ -349,7 +345,7 @@ def resync( # Create IndexerResyncBody from the list of options resync_body = IndexerResyncBody(options=indexer_resync_options) - self._client.indexers.resync(name, resync_body, **kwargs) + self._client.indexers.resync(indexer=name, resync_body=resync_body, **kwargs) @distributed_trace def get_indexer_status(self, name: str, **kwargs: Any) -> SearchIndexerStatus: @@ -421,15 +417,14 @@ def create_or_update_data_source_connection( """ 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, + match_condition=match_condition, prefer="return=representation", - error_map=error_map, + etag=data_source_connection.e_tag, skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, **kwargs ) @@ -532,13 +527,15 @@ def delete_data_source_connection( :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) + if isinstance(data_source_connection, str) and match_condition is not MatchConditions.Unconditionally: + raise ValueError("A model must be passed to use access conditions") try: name = data_source_connection.name # type: ignore + etag = data_source_connection.e_tag # type: ignore except AttributeError: name = data_source_connection - self._client.data_sources.delete(data_source_name=name, error_map=error_map, **kwargs) + etag = None + self._client.data_sources.delete(data_source_name=name, match_condition=match_condition, etag=etag, **kwargs) @distributed_trace def get_skillsets(self, *, select: Optional[List[str]] = None, **kwargs: Any) -> List[SearchIndexerSkillset]: @@ -611,13 +608,15 @@ def delete_skillset( :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) + if isinstance(skillset, str) and match_condition is not MatchConditions.Unconditionally: + raise ValueError("A model must be passed to use access conditions") try: name = skillset.name # type: ignore + etag = skillset.e_tag # type: ignore except AttributeError: name = skillset - self._client.skillsets.delete(name, error_map=error_map, **kwargs) + etag = None + self._client.skillsets.delete(name, match_condition=match_condition, etag=etag, **kwargs) @distributed_trace def create_skillset(self, skillset: SearchIndexerSkillset, **kwargs: Any) -> SearchIndexerSkillset: @@ -664,16 +663,15 @@ def create_or_update_skillset( """ 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 + match_condition=match_condition, prefer="return=representation", - error_map=error_map, + 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 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 index db82fab940b0..6e23e6bc0db7 100644 --- 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 @@ -12,15 +12,12 @@ 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 ..._generated.indexes.aio import SearchServiceClient as _SearchServiceClient from ...aio._search_client_async import SearchClient -from .._utils import ( - get_access_conditions, - normalize_endpoint, -) +from .._utils import normalize_endpoint from ..._api_versions import DEFAULT_VERSION from ..._headers_mixin import HeadersMixin -from ..._utils import get_authentication_policy +from ..._utils import DEFAULT_AUDIENCE from ..._version import SDK_MONIKER from ..models import ( SearchIndex, @@ -55,21 +52,19 @@ def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, AsyncTok 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 - ) + if not self._audience: + self._audience = DEFAULT_AUDIENCE + scope = self._audience.rstrip("/") + "/.default" + credential_scopes = [scope] + self._aad = not isinstance(credential, AzureKeyCredential) + self._client = _SearchServiceClient( + endpoint=endpoint, + credential=credential, + sdk_moniker=SDK_MONIKER, + api_version=self._api_version, + credential_scopes=credential_scopes, + **kwargs + ) async def __aenter__(self) -> "SearchIndexClient": await self._client.__aenter__() # pylint:disable=no-member @@ -171,7 +166,7 @@ async def get_index_statistics(self, index_name: str, **kwargs: Any) -> MutableM """ kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) result = await self._client.indexes.get_statistics(index_name, **kwargs) - return result.as_dict() + return result @distributed_trace_async async def delete_index( @@ -200,13 +195,15 @@ async def delete_index( :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) + if isinstance(index, str) and match_condition is not MatchConditions.Unconditionally: + raise ValueError("A model must be passed to use access conditions") try: index_name = index.name # type: ignore + etag = index.e_tag # type: ignore except AttributeError: index_name = index - await self._client.indexes.delete(index_name=index_name, error_map=error_map, **kwargs) + etag = None + await self._client.indexes.delete(index_name=index_name, match_condition=match_condition, etag=etag, **kwargs) @distributed_trace_async async def create_index(self, index: SearchIndex, **kwargs: Any) -> SearchIndex: @@ -271,15 +268,14 @@ async def create_or_update_index( :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, + match_condition=match_condition, allow_index_downtime=allow_index_downtime, prefer="return=representation", - error_map=error_map, + etag=index.e_tag, **kwargs ) return cast(SearchIndex, SearchIndex._from_generated(result)) # pylint:disable=protected-access @@ -307,9 +303,7 @@ async def analyze_text(self, index_name: str, analyze_request: AnalyzeTextOption """ 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 + index_name=index_name, request=analyze_request._to_generated(), **kwargs # pylint:disable=protected-access ) return result @@ -409,13 +403,17 @@ async def delete_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) + if isinstance(synonym_map, str) and match_condition is not MatchConditions.Unconditionally: + raise ValueError("A model must be passed to use access conditions") try: name = synonym_map.name # type: ignore + etag = synonym_map.e_tag # type: ignore except AttributeError: name = synonym_map - await self._client.synonym_maps.delete(synonym_map_name=name, error_map=error_map, **kwargs) + etag = None + await self._client.synonym_maps.delete( + synonym_map_name=name, match_condition=match_condition, etag=etag, **kwargs + ) @distributed_trace_async async def create_synonym_map(self, synonym_map: SynonymMap, **kwargs: Any) -> SynonymMap: @@ -460,14 +458,13 @@ async def create_or_update_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, + match_condition=match_condition, prefer="return=representation", - error_map=error_map, + etag=synonym_map.e_tag, **kwargs ) return cast(SynonymMap, SynonymMap._from_generated(result)) # pylint:disable=protected-access @@ -481,7 +478,7 @@ async def get_service_statistics(self, **kwargs) -> MutableMapping[str, Any]: """ kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) result = await self._client.get_service_statistics(**kwargs) - return result.as_dict() + return result @distributed_trace def list_index_stats_summary(self, **kwargs: Any) -> AsyncItemPaged[IndexStatisticsSummary]: @@ -538,7 +535,7 @@ async def get_alias(self, name: str, **kwargs) -> SearchAlias: """ kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) result = await self._client.aliases.get(name, **kwargs) - return result + return cast(SearchAlias, result) @distributed_trace_async async def delete_alias( @@ -567,13 +564,15 @@ async def delete_alias( :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) + if isinstance(alias, str) and match_condition is not MatchConditions.Unconditionally: + raise ValueError("A model must be passed to use access conditions") try: alias_name = alias.name # type: ignore + etag = alias.e_tag # type: ignore except AttributeError: alias_name = alias - await self._client.aliases.delete(alias_name=alias_name, error_map=error_map, **kwargs) + etag = None + await self._client.aliases.delete(alias_name=alias_name, match_condition=match_condition, etag=etag, **kwargs) @distributed_trace_async async def create_alias(self, alias: SearchAlias, **kwargs: Any) -> SearchAlias: @@ -596,7 +595,7 @@ async def create_alias(self, alias: SearchAlias, **kwargs: Any) -> SearchAlias: """ kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) result = await self._client.aliases.create(alias, **kwargs) - return result # pylint:disable=protected-access + return cast(SearchAlias, result) @distributed_trace_async async def create_or_update_alias( @@ -626,12 +625,15 @@ async def create_or_update_alias( :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 + alias_name=alias.name, + alias=alias, + match_condition=match_condition, + prefer="return=representation", + etag=alias.e_tag, + **kwargs ) - return result # pylint:disable=protected-access + return cast(SearchAlias, result) @distributed_trace_async async def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs) -> AsyncHttpResponse: @@ -644,7 +646,7 @@ async def send_request(self, request: HttpRequest, *, stream: bool = False, **kw :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 + return await self._client.send_request(request, stream=stream, **kwargs) # pylint:disable=protected-access @distributed_trace_async async def delete_agent( @@ -663,13 +665,13 @@ async def delete_agent( :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 + etag = agent.e_tag # type: ignore except AttributeError: agent_name = agent - await self._client.knowledge_agents.delete(agent_name=agent_name, error_map=error_map, **kwargs) + etag = None + await self._client.agents.delete(agent_name=agent_name, match_condition=match_condition, etag=etag, **kwargs) @distributed_trace_async async def create_agent(self, agent: KnowledgeAgent, **kwargs: Any) -> KnowledgeAgent: @@ -682,7 +684,7 @@ async def create_agent(self, agent: KnowledgeAgent, **kwargs: Any) -> KnowledgeA :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) + result = await self._client.agents.create(agent, **kwargs) return result @distributed_trace_async @@ -708,10 +710,13 @@ async def create_or_update_agent( :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 + result = await self._client.agents.create_or_update( + agent_name=agent.name, + knowledge_agent=agent, + match_condition=match_condition, + prefer="return=representation", + etag=agent.e_tag, + **kwargs ) return result @@ -726,8 +731,8 @@ async def get_agent(self, name: str, **kwargs: Any) -> 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 + result = await self._client.agents.get(name, **kwargs) + return cast(KnowledgeAgent, result) @distributed_trace def list_agents(self, **kwargs) -> AsyncItemPaged[KnowledgeAgent]: @@ -739,7 +744,7 @@ def list_agents(self, **kwargs) -> AsyncItemPaged[KnowledgeAgent]: """ kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) # pylint:disable=protected-access - return cast(AsyncItemPaged[KnowledgeAgent], self._client.knowledge_agents.list(**kwargs)) + return cast(AsyncItemPaged[KnowledgeAgent], self._client.agents.list(**kwargs)) @distributed_trace_async async def delete_knowledge_source( @@ -758,13 +763,13 @@ async def delete_knowledge_source( :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 + etag = knowledge_source.e_tag # type: ignore except AttributeError: source_name = knowledge_source - await self._client.knowledge_sources.delete(source_name=source_name, error_map=error_map, **kwargs) + etag = None + await self._client.sources.delete(source_name=source_name, match_condition=match_condition, etag=etag, **kwargs) @distributed_trace_async async def create_knowledge_source(self, knowledge_source: KnowledgeSource, **kwargs: Any) -> KnowledgeSource: @@ -777,7 +782,7 @@ async def create_knowledge_source(self, knowledge_source: KnowledgeSource, **kwa :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) + result = await self._client.sources.create(knowledge_source, **kwargs) return result @distributed_trace_async @@ -803,13 +808,12 @@ async def create_or_update_knowledge_source( :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( + result = await self._client.sources.create_or_update( source_name=knowledge_source.name, knowledge_source=knowledge_source, + match_condition=match_condition, prefer="return=representation", - error_map=error_map, + etag=knowledge_source.e_tag, **kwargs ) return result @@ -825,8 +829,8 @@ async def get_knowledge_source(self, name: str, **kwargs: Any) -> KnowledgeSourc :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 + result = await self._client.sources.get(name, **kwargs) + return cast(KnowledgeSource, result) @distributed_trace def list_knowledge_sources(self, **kwargs: Any) -> AsyncItemPaged[KnowledgeSource]: @@ -838,4 +842,4 @@ def list_knowledge_sources(self, **kwargs: Any) -> AsyncItemPaged[KnowledgeSourc """ kwargs["headers"] = self._merge_client_headers(kwargs.get("headers")) # pylint:disable=protected-access - return cast(AsyncItemPaged[KnowledgeSource], self._client.knowledge_sources.list(**kwargs)) + return cast(AsyncItemPaged[KnowledgeSource], self._client.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 index 97d0505db5af..8cbd25a8b91c 100644 --- 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 @@ -10,8 +10,8 @@ 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 ( +from ..._generated.indexes.aio import SearchServiceClient as _SearchServiceClient +from ..._generated.indexes.models import ( SkillNames, SearchIndexerStatus, DocumentKeysOrIds, @@ -19,13 +19,10 @@ IndexerResyncBody, ) from ..models import SearchIndexer, SearchIndexerSkillset, SearchIndexerDataSourceConnection -from .._utils import ( - get_access_conditions, - normalize_endpoint, -) +from .._utils import normalize_endpoint from ..._api_versions import DEFAULT_VERSION from ..._headers_mixin import HeadersMixin -from ..._utils import get_authentication_policy +from ..._utils import DEFAULT_AUDIENCE from ..._version import SDK_MONIKER @@ -49,22 +46,20 @@ def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, AsyncTok 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 - ) + self._audience = kwargs.pop("audience", None) + if not self._audience: + self._audience = DEFAULT_AUDIENCE + scope = self._audience.rstrip("/") + "/.default" + credential_scopes = [scope] + self._aad = not isinstance(credential, AzureKeyCredential) + self._client = _SearchServiceClient( + endpoint=endpoint, + credential=credential, + sdk_moniker=SDK_MONIKER, + api_version=self._api_version, + credential_scopes=credential_scopes, + **kwargs + ) async def __aenter__(self) -> "SearchIndexerClient": await self._client.__aenter__() @@ -129,15 +124,14 @@ async def create_or_update_indexer( :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, + match_condition=match_condition, prefer="return=representation", - error_map=error_map, + 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 @@ -233,13 +227,15 @@ async def delete_indexer( :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) + if isinstance(indexer, str) and match_condition is not MatchConditions.Unconditionally: + raise ValueError("A model must be passed to use access conditions") try: name = indexer.name # type: ignore + etag = indexer.e_tag # type: ignore except AttributeError: name = indexer - await self._client.indexers.delete(name, error_map=error_map, **kwargs) + etag = None + await self._client.indexers.delete(name, etag=etag, match_condition=match_condition, **kwargs) @distributed_trace_async async def run_indexer(self, name: str, **kwargs: Any) -> None: @@ -336,7 +332,7 @@ async def resync( # Create IndexerResyncBody from the list of options resync_body = IndexerResyncBody(options=indexer_resync_options) - await self._client.indexers.resync(name, resync_body, **kwargs) + await self._client.indexers.resync(indexer_name=name, resync_body=resync_body, **kwargs) return @distributed_trace_async @@ -408,19 +404,15 @@ async def create_or_update_data_source_connection( :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, + match_condition=match_condition, prefer="return=representation", - error_map=error_map, + etag=data_source_connection.e_tag, skip_indexer_reset_requirement_for_cache=skip_indexer_reset_requirement_for_cache, **kwargs ) @@ -453,16 +445,17 @@ async def delete_data_source_connection( :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) + if isinstance(data_source_connection, str) and match_condition is not MatchConditions.Unconditionally: + raise ValueError("A model must be passed to use access conditions") try: name = data_source_connection.name # type: ignore + etag = data_source_connection.e_tag # type: ignore except AttributeError: name = data_source_connection - await self._client.data_sources.delete(data_source_name=name, error_map=error_map, **kwargs) + etag = None + await self._client.data_sources.delete( + data_source_name=name, etag=etag, match_condition=match_condition, **kwargs + ) @distributed_trace_async async def get_data_source_connection( @@ -603,13 +596,15 @@ async def delete_skillset( :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) + if isinstance(skillset, str) and match_condition is not MatchConditions.Unconditionally: + raise ValueError("A model must be passed to use access conditions") try: name = skillset.name # type: ignore + etag = skillset.e_tag # type: ignore except AttributeError: name = skillset - await self._client.skillsets.delete(name, error_map=error_map, **kwargs) + etag = None + await self._client.skillsets.delete(name, etag=etag, match_condition=match_condition, **kwargs) @distributed_trace_async async def create_skillset(self, skillset: SearchIndexerSkillset, **kwargs: Any) -> SearchIndexerSkillset: @@ -654,15 +649,14 @@ async def create_or_update_skillset( """ 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 + match_condition=match_condition, prefer="return=representation", - error_map=error_map, + 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 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..c91542c587be 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 @@ -32,8 +32,7 @@ SearchIndex, ) from . import _edm -from ..._generated.models import SuggestOptions -from .._generated.models import ( +from ..._generated.indexes.models import ( SearchAlias, AIServicesAccountIdentity, AIServicesAccountKey, @@ -61,9 +60,9 @@ BM25SimilarityAlgorithm, CharFilter, CharFilterName, + ChatCompletionCommonModelParameters, ChatCompletionExtraParametersBehavior, ChatCompletionResponseFormat, - ChatCompletionResponseFormatJsonSchemaProperties, ChatCompletionResponseFormatType, ChatCompletionSchema, ChatCompletionSkill, @@ -74,7 +73,6 @@ CognitiveServicesAccount, CognitiveServicesAccountKey, CommonGramTokenFilter, - CommonModelParameters, ConditionalSkill, CorsOptions, CustomEntity, @@ -137,9 +135,9 @@ KeyPhraseExtractionSkill, KeyPhraseExtractionSkillLanguage, KeywordMarkerTokenFilter, - KeywordTokenizerV2, + KeywordTokenizer, KnowledgeAgent, - KnowledgeAgentAzureOpenAIModel, + KnowledgeAgentAzureOpenAiModel, KnowledgeAgentModel, KnowledgeAgentOutputConfiguration, KnowledgeAgentModelKind, @@ -176,7 +174,7 @@ OcrSkill, OcrSkillLanguage, OutputFieldMappingEntry, - PathHierarchyTokenizerV2, + PathHierarchyTokenizer, PatternCaptureTokenFilter, PatternReplaceCharFilter, PatternReplaceTokenFilter, @@ -296,15 +294,6 @@ SearchFieldDataType = _edm - -class KeywordTokenizer(KeywordTokenizerV2): - pass - - -class PathHierarchyTokenizer(PathHierarchyTokenizerV2): - pass - - __all__ = ( "AIServicesAccountIdentity", "AIServicesAccountKey", @@ -333,10 +322,10 @@ class PathHierarchyTokenizer(PathHierarchyTokenizerV2): "BM25SimilarityAlgorithm", "CharFilter", "CharFilterName", + "ChatCompletionCommonModelParameters", "ChatCompletionExtraParametersBehavior", "ChatCompletionResponseFormat", "ChatCompletionResponseFormatType", - "ChatCompletionResponseFormatJsonSchemaProperties", "ChatCompletionSchema", "ChatCompletionSkill", "CjkBigramTokenFilter", @@ -346,7 +335,6 @@ class PathHierarchyTokenizer(PathHierarchyTokenizerV2): "CognitiveServicesAccount", "CognitiveServicesAccountKey", "CommonGramTokenFilter", - "CommonModelParameters", "ComplexField", "ConditionalSkill", "CorsOptions", @@ -417,7 +405,7 @@ class PathHierarchyTokenizer(PathHierarchyTokenizerV2): "KeywordTokenizer", "LanguageDetectionSkill", "KnowledgeAgent", - "KnowledgeAgentAzureOpenAIModel", + "KnowledgeAgentAzureOpenAiModel", "KnowledgeAgentModel", "KnowledgeAgentModelKind", "KnowledgeAgentOutputConfiguration", @@ -537,7 +525,6 @@ class PathHierarchyTokenizer(PathHierarchyTokenizerV2): "StopAnalyzer", "StopwordsList", "StopwordsTokenFilter", - "SuggestOptions", "SynonymMap", "SynonymTokenFilter", "TagScoringFunction", 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 index 3ed8dfa370f6..bc8cd4a41aca 100644 --- 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 @@ -3,11 +3,13 @@ # 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 import Any, Dict, Union, List, Optional, cast +import json from typing_extensions import Self -from .._generated._utils import serialization as _serialization +from azure.core.exceptions import DeserializationError +from ..._generated._utils.model_base import Model from ._edm import Collection, ComplexType, String -from .._generated.models import ( +from ..._generated.indexes.models import ( SearchField as _SearchField, SearchIndex as _SearchIndex, PatternTokenizer as _PatternTokenizer, @@ -39,7 +41,7 @@ __all__ = ("ComplexField", "SearchableField", "SimpleField") -class SearchField(_serialization.Model): +class SearchField(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. @@ -266,7 +268,7 @@ def _to_generated(self) -> _SearchField: @classmethod def _from_generated(cls, search_field) -> Optional[Self]: - if not search_field: + if search_field is None: return None # pylint:disable=protected-access fields = ( @@ -301,66 +303,53 @@ def _from_generated(cls, search_field) -> Optional[Self]: vector_encoding_format=search_field.vector_encoding_format, ) - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> MutableMapping[str, Any]: + def serialize(self, **kwargs: Any) -> str: + # pylint: disable=unused-argument """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 + :returns: A dict JSON compatible string + :rtype: str """ - return self._to_generated().serialize(keep_readonly=keep_readonly, **kwargs) + return json.dumps(self._to_generated().as_dict()) # type: ignore @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Optional[Self]: # type: ignore + def deserialize(cls, data: Any, **kwargs) -> Optional[Self]: # type: ignore + # pylint: disable=unused-argument """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. + :param str data: A JSON str using RestAPI structure. :returns: A SearchField instance :raises DeserializationError: if something went wrong """ - return cls._from_generated(_SearchField.deserialize(data, content_type=content_type)) + try: + obj_dict = json.loads(data) + obj = _SearchField(obj_dict) + return cls._from_generated(obj) + except json.JSONDecodeError as err: + raise DeserializationError("Failed to deserialize data.") from err - 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]: + def as_dict(self, **kwargs: Any) -> Dict[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 - ) + return self._to_generated().as_dict(**kwargs) # type: ignore @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) + def from_dict(cls, data: Any, **kwargs: Any) -> Optional[Self]: # pylint: disable=unused-argument + """Parse a dict return a model. :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) - ) + try: + obj = _SearchField(data) + return cls._from_generated(obj) + except json.JSONDecodeError as err: + raise DeserializationError("Failed to deserialize data.") from err def SimpleField( @@ -613,7 +602,7 @@ def ComplexField( return SearchField(**result) -class SearchIndex(_serialization.Model): +class SearchIndex(Model): # pylint: disable=too-many-instance-attributes """Represents a search index definition, which describes the fields and search behavior of an index. @@ -694,7 +683,7 @@ def __init__( e_tag: Optional[str] = None, **kwargs ): - super().__init__(**kwargs) + super().__init__() self.name = name self.fields = fields self.description = description @@ -754,7 +743,7 @@ def _to_generated(self) -> _SearchIndex: @classmethod def _from_generated(cls, search_index) -> Optional[Self]: - if not search_index: + if search_index is None: return None if search_index.analyzers: analyzers = [unpack_analyzer(x) for x in search_index.analyzers] # type: ignore @@ -802,67 +791,57 @@ def _from_generated(cls, search_index) -> Optional[Self]: permission_filter_option=search_index.permission_filter_option, ) - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> MutableMapping[str, Any]: + def serialize(self, **kwargs: Any) -> str: + # pylint: disable=unused-argument """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 + :returns: A dict JSON compatible string + :rtype: str """ - return self._to_generated().serialize(keep_readonly=keep_readonly, **kwargs) + return json.dumps(self._to_generated().as_dict()) @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Optional[Self]: # type: ignore + def deserialize(cls, data: Any, **kwargs) -> Optional[Self]: # type: ignore + # pylint: disable=unused-argument """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. + :param str data: A JSON str using RestAPI structure. :returns: A SearchIndex instance :rtype: SearchIndex :raises DeserializationError: if something went wrong """ - return cls._from_generated(_SearchIndex.deserialize(data, content_type=content_type)) + try: + obj_dict = json.loads(data) + obj = _SearchIndex(obj_dict) + return cls._from_generated(obj) + except json.JSONDecodeError as err: + raise DeserializationError("Failed to deserialize data.") from err - 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]: + def as_dict(self, **kwargs: Any) -> Dict[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 - ) + return self._to_generated().as_dict(**kwargs) # type: ignore @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) + """Parse a dict return a model. :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) - ) + try: + obj = _SearchIndex(data) + return cls._from_generated(obj) + except json.JSONDecodeError as err: + raise DeserializationError("Failed to deserialize data.") from err def pack_search_field(search_field: SearchField) -> _SearchField: 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..89a08be8075b 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 @@ -5,12 +5,14 @@ # license information. # -------------------------------------------------------------------------- -from typing import Any, List, Optional, MutableMapping, Dict, Callable, Union +from typing import Any, List, Optional, Dict, Union from enum import Enum +import json from typing_extensions import Self from azure.core import CaseInsensitiveEnumMeta -from .._generated._utils import serialization as _serialization -from .._generated.models import ( +from azure.core.exceptions import DeserializationError +from ..._generated._utils.model_base import Model +from ..._generated.indexes.models import ( LexicalAnalyzer, LexicalTokenizer, AnalyzeRequest, @@ -44,7 +46,7 @@ DELIMITER = "|" -class SearchIndexerSkillset(_serialization.Model): +class SearchIndexerSkillset(Model): """A list of skills. All required parameters must be populated in order to send to Azure. @@ -89,7 +91,7 @@ def __init__( encryption_key: Optional["SearchResourceEncryptionKey"] = None, **kwargs: Any ) -> None: - super().__init__(**kwargs) + super().__init__() self.name = name self.description = description self.skills = skills @@ -108,6 +110,9 @@ def _to_generated(self) -> _SearchIndexerSkillset: generated_skills.append(skill) assert len(generated_skills) == len(self.skills) encryption_key = getattr(self, "encryption_key", None) + encryption_key_patched = ( + None if encryption_key is None else encryption_key._to_generated() # pylint:disable=protected-access + ) return _SearchIndexerSkillset( name=getattr(self, "name", ""), description=getattr(self, "description", None), @@ -116,14 +121,12 @@ def _to_generated(self) -> _SearchIndexerSkillset: 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 - ), + encryption_key=encryption_key_patched, ) @classmethod def _from_generated(cls, skillset) -> Optional[Self]: - if not skillset: + if skillset is None: return None custom_skills = [] for skill in skillset.skills: @@ -141,67 +144,57 @@ def _from_generated(cls, skillset) -> Optional[Self]: kwargs["skills"] = custom_skills return cls(**kwargs) - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> MutableMapping[str, Any]: + def serialize(self, **kwargs: Any) -> str: + # pylint: disable=unused-argument """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 + :returns: A dict JSON compatible string + :rtype: str """ - return self._to_generated().serialize(keep_readonly=keep_readonly, **kwargs) # type: ignore + return json.dumps(self._to_generated().as_dict()) # type: ignore @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Optional[Self]: # type: ignore + def deserialize(cls, data: Any, **kwargs) -> Optional[Self]: # type: ignore + # pylint: disable=unused-argument """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. + :param str data: A JSON str using RestAPI structure. :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]: + try: + obj_dict = json.loads(data) + obj = _SearchIndexerSkillset(obj_dict) + return cls._from_generated(obj) + except json.JSONDecodeError as err: + raise DeserializationError("Failed to deserialize data.") from err + + def as_dict(self, **kwargs: Any) -> Dict[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 - ) + return self._to_generated().as_dict(**kwargs) # type: ignore @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) + """Parse a dict return a model. :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) - ) + try: + obj = _SearchIndexerSkillset(data) + return cls._from_generated(obj) + except json.JSONDecodeError as err: + raise DeserializationError("Failed to deserialize data.") from err class EntityRecognitionSkillVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -263,28 +256,6 @@ class EntityRecognitionSkill(SearchIndexerSkill): :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) @@ -319,7 +290,7 @@ def _to_generated(self): @classmethod def _from_generated(cls, skill): - if not skill: + if skill is None: return None kwargs = skill.as_dict() if isinstance(skill, _EntityRecognitionSkillV3): @@ -383,25 +354,6 @@ class SentimentSkill(SearchIndexerSkill): :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) @@ -433,7 +385,7 @@ def _to_generated(self): @classmethod def _from_generated(cls, skill): - if not skill: + if skill is None: return None kwargs = skill.as_dict() if isinstance(skill, _SentimentSkillV3): @@ -441,8 +393,46 @@ def _from_generated(cls, skill): return None -class AnalyzeTextOptions(_serialization.Model): - """Specifies some text and analysis components used to break that text into tokens.""" +class AnalyzeTextOptions(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 Azure. + + :ivar text: Required. The text to break into tokens. + :vartype text: str + :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. 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". + :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. 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: 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] + """ def __init__( self, @@ -455,43 +445,7 @@ def __init__( 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) + super().__init__() self.text = text self.analyzer_name = analyzer_name self.tokenizer_name = tokenizer_name @@ -499,7 +453,7 @@ def __init__( self.token_filters = token_filters self.char_filters = char_filters - def _to_analyze_request(self): + def _to_generated(self): return AnalyzeRequest( text=self.text, analyzer=self.analyzer_name, @@ -510,8 +464,8 @@ def _to_analyze_request(self): ) @classmethod - def _from_analyze_request(cls, analyze_request) -> Optional[Self]: - if not analyze_request: + def _from_generated(cls, analyze_request) -> Optional[Self]: + if analyze_request is None: return None return cls( text=analyze_request.text, @@ -522,67 +476,54 @@ def _from_analyze_request(cls, analyze_request) -> Optional[Self]: char_filters=analyze_request.char_filters, ) - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> MutableMapping[str, Any]: + def serialize(self, **kwargs: Any) -> str: + # pylint: disable=unused-argument """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 + :returns: A dict JSON compatible string + :rtype: str """ - return self._to_analyze_request().serialize(keep_readonly=keep_readonly, **kwargs) # type: ignore + return json.dumps(self._to_generated().as_dict()) # type: ignore @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Optional[Self]: # type: ignore + def deserialize(cls, data: Any, **kwargs) -> Optional[Self]: # type: ignore + # pylint: disable=unused-argument """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]: + try: + obj_dict = json.loads(data) + obj = AnalyzeRequest(obj_dict) + return cls._from_generated(obj) + except json.JSONDecodeError as err: + raise DeserializationError("Failed to deserialize data.") from err + + def as_dict(self, **kwargs: Any) -> Dict[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 - ) + return self._to_generated().as_dict(**kwargs) # type: ignore @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) + def from_dict(cls, data: Any, **kwargs) -> Optional[Self]: # type: ignore + # pylint: disable=unused-argument + """Parse a dict return a model. :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 + :returns: An 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) - ) + try: + obj = AnalyzeRequest(data) + return cls._from_generated(obj) + except json.JSONDecodeError as err: + raise DeserializationError("Failed to deserialize data.") from err class CustomAnalyzer(LexicalAnalyzer): @@ -617,11 +558,14 @@ class CustomAnalyzer(LexicalAnalyzer): """ def __init__(self, **kwargs): + tokenizer_name = kwargs.pop("tokenizer_name", None) + token_filters = kwargs.pop("token_filters", None) + char_filters = kwargs.pop("char_filters", None) 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) + self.tokenizer_name = tokenizer_name + self.token_filters = token_filters + self.char_filters = char_filters def _to_generated(self): return _CustomAnalyzer( @@ -634,7 +578,7 @@ def _to_generated(self): @classmethod def _from_generated(cls, custom_analyzer): - if not custom_analyzer: + if custom_analyzer is None: return None return cls( name=custom_analyzer.name, @@ -668,27 +612,20 @@ class PatternAnalyzer(LexicalAnalyzer): :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, **kwargs): + lower_case_terms = kwargs.pop("lower_case_terms", True) + pattern = kwargs.pop("pattern", r"\W+") + flags = kwargs.pop("flags", None) + stopwords = kwargs.pop("stopwords", None) 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) + self.lower_case_terms = lower_case_terms + self.pattern = pattern + self.flags = flags + self.stopwords = stopwords def _to_generated(self): - if not self.flags: + if self.flags is None: flags = None else: flags = DELIMITER.join(self.flags) @@ -702,9 +639,9 @@ def _to_generated(self): @classmethod def _from_generated(cls, pattern_analyzer): - if not pattern_analyzer: + if pattern_analyzer is None: return None - if not pattern_analyzer.flags: + if pattern_analyzer.flags is None: flags = None else: flags = pattern_analyzer.flags.split(DELIMITER) @@ -739,25 +676,18 @@ class PatternTokenizer(LexicalTokenizer): :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, **kwargs): + pattern = kwargs.pop("pattern", r"\W+") + flags = kwargs.pop("flags", None) + group = kwargs.pop("group", -1) 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) + self.pattern = pattern + self.flags = flags + self.group = group def _to_generated(self): - if not self.flags: + if self.flags is None: flags = None else: flags = DELIMITER.join(self.flags) @@ -770,9 +700,9 @@ def _to_generated(self): @classmethod def _from_generated(cls, pattern_tokenizer): - if not pattern_tokenizer: + if pattern_tokenizer is None: return None - if not pattern_tokenizer.flags: + if pattern_tokenizer.flags is None: flags = None else: flags = pattern_tokenizer.flags.split(DELIMITER) @@ -784,7 +714,7 @@ def _from_generated(cls, pattern_tokenizer): ) -class SearchResourceEncryptionKey(_serialization.Model): +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 in Azure Cognitive Search, such as indexes and synonym maps. @@ -824,7 +754,7 @@ def __init__( identity: Optional[SearchIndexerDataIdentity] = None, **kwargs ): - super().__init__(**kwargs) + super().__init__() self.key_name = key_name self.key_version = key_version self.vault_uri = vault_uri @@ -850,7 +780,7 @@ def _to_generated(self): @classmethod def _from_generated(cls, search_resource_encryption_key) -> Optional[Self]: - if not search_resource_encryption_key: + if search_resource_encryption_key is None: return None if search_resource_encryption_key.access_credentials: application_id = search_resource_encryption_key.access_credentials.application_id @@ -867,71 +797,59 @@ def _from_generated(cls, search_resource_encryption_key) -> Optional[Self]: identity=search_resource_encryption_key.identity, ) - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> MutableMapping[str, Any]: + def serialize(self, **kwargs: Any) -> str: + # pylint: disable=unused-argument """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 + :returns: A dict JSON compatible string + :rtype: str """ - return self._to_generated().serialize(keep_readonly=keep_readonly, **kwargs) # type: ignore + return json.dumps(self._to_generated().as_dict()) # type: ignore @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Optional[Self]: # type: ignore + def deserialize(cls, data: Any, **kwargs) -> Optional[Self]: # type: ignore + # pylint: disable=unused-argument """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. + :param str data: A JSON str using RestAPI structure. :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]: + try: + obj_dict = json.loads(data) + obj = _SearchResourceEncryptionKey(obj_dict) + return cls._from_generated(obj) + except json.JSONDecodeError as err: + raise DeserializationError("Failed to deserialize data.") from err + + def as_dict(self, **kwargs: Any) -> Dict[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 - ) + return self._to_generated().as_dict(**kwargs) # type: ignore @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) + """Parse a dict return a model. :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) - ) + try: + obj = _SearchResourceEncryptionKey(data) + return cls._from_generated(obj) + except json.JSONDecodeError as err: + raise DeserializationError("Failed to deserialize data.") from err -class SynonymMap(_serialization.Model): +class SynonymMap(Model): """Represents a synonym map definition. Variables are only populated by the server, and will be ignored when sending a request. @@ -970,25 +888,25 @@ def __init__( e_tag: Optional[str] = None, **kwargs ): - super().__init__(**kwargs) + super().__init__() self.name = name self.synonyms = synonyms self.encryption_key = encryption_key self.e_tag = e_tag def _to_generated(self): + # pylint:disable=protected-access + encryption_key = None if self.encryption_key is None else self.encryption_key._to_generated() 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 - ), + encryption_key=encryption_key, e_tag=self.e_tag, ) @classmethod def _from_generated(cls, synonym_map) -> Optional[Self]: - if not synonym_map: + if synonym_map is None: return None return cls( name=synonym_map.name, @@ -998,70 +916,58 @@ def _from_generated(cls, synonym_map) -> Optional[Self]: e_tag=synonym_map.e_tag, ) - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> MutableMapping[str, Any]: + def serialize(self, **kwargs: Any) -> str: + # pylint: disable=unused-argument """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 + :returns: A dict JSON compatible string + :rtype: str """ - return self._to_generated().serialize(keep_readonly=keep_readonly, **kwargs) # type: ignore + return json.dumps(self._to_generated().as_dict()) # type: ignore @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Optional[Self]: # type: ignore + def deserialize(cls, data: Any, **kwargs) -> Optional[Self]: # type: ignore + # pylint: disable=unused-argument """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. + :param str data: A JSON str using RestAPI structure. :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]: + try: + obj_dict = json.loads(data) + obj = _SynonymMap(obj_dict) + return cls._from_generated(obj) + except json.JSONDecodeError as err: + raise DeserializationError("Failed to deserialize data.") from err + + def as_dict(self, **kwargs: Any) -> Dict[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 - ) + return self._to_generated().as_dict(**kwargs) # type: ignore @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) + def from_dict(cls, data: Any, **kwargs) -> Optional[Self]: # type: ignore + # pylint: disable=unused-argument + """Parse a dict return a model. :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) - ) + try: + obj = _SynonymMap(data) + return cls._from_generated(obj) + except json.JSONDecodeError as err: + raise DeserializationError("Failed to deserialize data.") from err -class SearchIndexerDataSourceConnection(_serialization.Model): # pylint: disable=too-many-instance-attributes +class SearchIndexerDataSourceConnection(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. @@ -1120,7 +1026,7 @@ def __init__( encryption_key: Optional[SearchResourceEncryptionKey] = None, **kwargs ): - super().__init__(**kwargs) + super().__init__() self.name = name self.description = description self.type = type @@ -1139,6 +1045,8 @@ def _to_generated(self): else: connection_string = self.connection_string credentials = DataSourceCredentials(connection_string=connection_string) + # pylint:disable=protected-access + encryption_key = None if self.encryption_key is None else self.encryption_key._to_generated() return _SearchIndexerDataSource( name=self.name, description=self.description, @@ -1148,16 +1056,14 @@ def _to_generated(self): 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 - ), + encryption_key=encryption_key, 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: + if search_indexer_data_source is None: return None connection_string = ( search_indexer_data_source.credentials.connection_string if search_indexer_data_source.credentials else "" @@ -1182,71 +1088,60 @@ def _from_generated(cls, search_indexer_data_source) -> Optional[Self]: indexer_permission_options=search_indexer_data_source.indexer_permission_options, ) - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> MutableMapping[str, Any]: + def serialize(self, **kwargs: Any) -> str: + # pylint: disable=unused-argument """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 + :returns: A dict JSON compatible string + :rtype: str """ - return self._to_generated().serialize(keep_readonly=keep_readonly, **kwargs) # type: ignore + return json.dumps(self._to_generated().as_dict()) # type: ignore @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Optional[Self]: # type: ignore + def deserialize(cls, data: Any, **kwargs) -> Optional[Self]: # type: ignore + # pylint: disable=unused-argument """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. + :param str data: A JSON str using RestAPI structure. :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]: + try: + obj_dict = json.loads(data) + obj = _SearchIndexerDataSource(obj_dict) + return cls._from_generated(obj) + except json.JSONDecodeError as err: + raise DeserializationError("Failed to deserialize data.") from err + + def as_dict(self, **kwargs: Any) -> Dict[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 - ) + return self._to_generated().as_dict(**kwargs) # type: ignore @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) + def from_dict(cls, data: Any, **kwargs) -> Optional[Self]: # type: ignore + # pylint: disable=unused-argument + """Parse a dict return a model. :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) - ) + try: + obj_dict = json.loads(data) + obj = _SearchIndexerDataSource(obj_dict) + return cls._from_generated(obj) + except json.JSONDecodeError as err: + raise DeserializationError("Failed to deserialize data.") from err def pack_analyzer(analyzer): - if not analyzer: + if analyzer is None: return None if isinstance(analyzer, (PatternAnalyzer, CustomAnalyzer)): return analyzer._to_generated() # pylint:disable=protected-access @@ -1254,7 +1149,7 @@ def pack_analyzer(analyzer): def unpack_analyzer(analyzer): - if not analyzer: + if analyzer is None: return None if isinstance(analyzer, _PatternAnalyzer): return PatternAnalyzer._from_generated(analyzer) # pylint:disable=protected-access @@ -1263,7 +1158,7 @@ def unpack_analyzer(analyzer): return analyzer -class SearchIndexer(_serialization.Model): # pylint: disable=too-many-instance-attributes +class SearchIndexer(Model): # pylint: disable=too-many-instance-attributes """Represents an indexer. All required parameters must be populated in order to send to server. @@ -1326,47 +1221,7 @@ def __init__( 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) + super().__init__() self.name = name self.description = description self.data_source_name = data_source_name @@ -1382,6 +1237,8 @@ def __init__( self.cache = cache def _to_generated(self): + # pylint:disable=protected-access + encryption_key = None if self.encryption_key is None else self.encryption_key._to_generated() return _SearchIndexer( name=self.name, description=self.description, @@ -1394,15 +1251,13 @@ def _to_generated(self): 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 - ), + encryption_key=encryption_key, cache=self.cache, ) @classmethod def _from_generated(cls, search_indexer) -> Optional[Self]: - if not search_indexer: + if search_indexer is None: return None return cls( name=search_indexer.name, @@ -1421,23 +1276,28 @@ def _from_generated(cls, search_indexer) -> Optional[Self]: cache=search_indexer.cache, ) - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> MutableMapping[str, Any]: + def serialize(self, **kwargs: Any) -> str: + # pylint: disable=unused-argument """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 + :returns: A dict JSON compatible string + :rtype: str """ - return self._to_generated().serialize(keep_readonly=keep_readonly, **kwargs) # type: ignore + return json.dumps(self._to_generated().as_dict()) # type: ignore @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Optional[Self]: # type: ignore + def deserialize(cls, data: Any, **kwargs) -> Optional[Self]: # type: ignore + # pylint: disable=unused-argument """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. + :param str data: A JSON str using RestAPI structure. :returns: A SearchIndexer instance :rtype: SearchIndexer :raises DeserializationError: if something went wrong """ - return cls._from_generated(_SearchIndexer.deserialize(data, content_type=content_type)) + try: + obj_dict = json.loads(data) + obj = _SearchIndexer(obj_dict) + return cls._from_generated(obj) + except json.JSONDecodeError as err: + raise DeserializationError("Failed to deserialize data.") from err diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/__init__.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/agent/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebase/__init__.py diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/_agent_client.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_agent_client.py similarity index 60% rename from sdk/search/azure-search-documents/azure/search/documents/agent/_agent_client.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_agent_client.py index f53ab27ca7bc..fd62ab31be63 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/agent/_agent_client.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/_agent_client.py @@ -8,14 +8,13 @@ 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 .._generated.knowledgebase import KnowledgeBaseRetrievalClient as _KnowledgeBaseRetrievalClient +from .._generated.knowledgebase.models import ( + KnowledgeBaseRetrievalRequest, + KnowledgeBaseRetrievalResponse, ) from .._headers_mixin import HeadersMixin -from .._utils import get_authentication_policy +from .._utils import DEFAULT_AUDIENCE from .._version import SDK_MONIKER @@ -35,7 +34,7 @@ class KnowledgeAgentRetrievalClient(HeadersMixin): """ _ODATA_ACCEPT: str = "application/json;odata.metadata=none" - _client: _KnowledgeAgentRetrievalClient + _client: _KnowledgeBaseRetrievalClient def __init__( self, endpoint: str, agent_name: str, credential: Union[AzureKeyCredential, TokenCredential], **kwargs: Any @@ -44,27 +43,20 @@ def __init__( 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._audience = kwargs.pop("audience", None) + if not self._audience: + self._audience = DEFAULT_AUDIENCE + scope = self._audience.rstrip("/") + "/.default" + credential_scopes = [scope] + self._aad = not isinstance(credential, AzureKeyCredential) + self._client = _KnowledgeBaseRetrievalClient( + endpoint=endpoint, + credential=credential, + sdk_moniker=SDK_MONIKER, + api_version=self._api_version, + credential_scopes=credential_scopes, + **kwargs + ) self.knowledge_retrieval = self._client.knowledge_retrieval def __repr__(self) -> str: @@ -83,15 +75,11 @@ def close(self) -> None: @distributed_trace def retrieve( self, - retrieval_request: Union[KnowledgeAgentRetrievalRequest, IO[bytes]], - x_ms_query_source_authorization: Optional[str] = None, - request_options: Optional[RequestOptions] = None, + retrieval_request: Union[KnowledgeBaseRetrievalRequest, IO[bytes]], + query_source_authorization: Optional[str] = None, **kwargs: Any - ) -> KnowledgeAgentRetrievalResponse: + ) -> KnowledgeBaseRetrievalResponse: 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 + retrieval_request=retrieval_request, query_source_authorization=query_source_authorization, **kwargs ) diff --git a/sdk/search/azure-search-documents/azure/search/documents/agent/aio/__init__.py b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/__init__.py similarity index 100% rename from sdk/search/azure-search-documents/azure/search/documents/agent/aio/__init__.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/__init__.py 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/knowledgebase/aio/_agent_client_async.py similarity index 61% rename from sdk/search/azure-search-documents/azure/search/documents/agent/aio/_agent_client_async.py rename to sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_agent_client_async.py index de658044da46..0b861ad77dba 100644 --- a/sdk/search/azure-search-documents/azure/search/documents/agent/aio/_agent_client_async.py +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/aio/_agent_client_async.py @@ -8,12 +8,11 @@ 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 ..._utils import DEFAULT_AUDIENCE +from ..._generated.knowledgebase.aio import KnowledgeBaseRetrievalClient as _KnowledgeBaseRetrievalClient +from ..._generated.knowledgebase.models import ( + KnowledgeBaseRetrievalRequest, + KnowledgeBaseRetrievalResponse, ) from ..._api_versions import DEFAULT_VERSION from ..._headers_mixin import HeadersMixin @@ -36,7 +35,7 @@ class KnowledgeAgentRetrievalClient(HeadersMixin): """ _ODATA_ACCEPT: str = "application/json;odata.metadata=none" - _client: _KnowledgeAgentRetrievalClient + _client: _KnowledgeBaseRetrievalClient def __init__( self, endpoint: str, agent_name: str, credential: Union[AzureKeyCredential, AsyncTokenCredential], **kwargs: Any @@ -45,27 +44,20 @@ def __init__( 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._audience = kwargs.pop("audience", None) + if not self._audience: + self._audience = DEFAULT_AUDIENCE + scope = self._audience.rstrip("/") + "/.default" + credential_scopes = [scope] + self._aad = not isinstance(credential, AzureKeyCredential) + self._client = _KnowledgeBaseRetrievalClient( + endpoint=endpoint, + credential=credential, + sdk_moniker=SDK_MONIKER, + api_version=self._api_version, + credential_scopes=credential_scopes, + **kwargs + ) self.knowledge_retrieval = self._client.knowledge_retrieval def __repr__(self) -> str: @@ -84,15 +76,11 @@ async def close(self) -> None: @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, + retrieval_request: Union[KnowledgeBaseRetrievalRequest, IO[bytes]], + query_source_authorization: Optional[str] = None, **kwargs: Any - ) -> KnowledgeAgentRetrievalResponse: + ) -> KnowledgeBaseRetrievalResponse: 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 + retrieval_request=retrieval_request, query_source_authorization=query_source_authorization, **kwargs ) 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..fff6fdf3ea6a --- /dev/null +++ b/sdk/search/azure-search-documents/azure/search/documents/knowledgebase/models/__init__.py @@ -0,0 +1,102 @@ +# -------------------------------------------------------------------------- +# +# 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.knowledgebase.models import ( + 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, +) + + +__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", +) 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 index 3c166e74983c..8c1f8af946d5 100644 --- 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 @@ -92,7 +92,7 @@ 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.key = actions[0].get("id") result.status_code = 400 result.succeeded = False self.uploaded = self.uploaded + len(actions) - 1 @@ -113,7 +113,7 @@ 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.key = actions[0].get("id") result.status_code = 400 result.succeeded = False self.uploaded = self.uploaded + len(actions) - 1 @@ -136,7 +136,7 @@ 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.key = actions[0].get("id") result.status_code = 200 result.succeeded = True return [result] 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 index c41691889a96..f55a2b1112da 100644 --- 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 @@ -14,15 +14,13 @@ class TestSearchClientAsync: @await_prepared_test - @mock.patch( - "azure.search.documents._generated.aio.operations._documents_operations.DocumentsOperations.search_post" - ) + @mock.patch("azure.search.documents._generated.aio.operations._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"})] + search_result.results = [SearchResult({"key": "val"})] mock_search_post.return_value = search_result await result.__anext__() result._first_page_iterator_instance.continuation_token = "fake token" 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..e594227486b3 100644 --- a/sdk/search/azure-search-documents/tests/search_service_preparer.py +++ b/sdk/search/azure-search-documents/tests/search_service_preparer.py @@ -98,7 +98,7 @@ def _set_up_index(service_name, endpoint, cred, schema, index_batch): # optionally load data into the index if index_batch and schema: - batch = IndexBatch.deserialize(index_batch) + batch = IndexBatch(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_buffered_sender.py b/sdk/search/azure-search-documents/tests/test_buffered_sender.py index 5af0b3d5efbf..3bf30d932d0b 100644 --- a/sdk/search/azure-search-documents/tests/test_buffered_sender.py +++ b/sdk/search/azure-search-documents/tests/test_buffered_sender.py @@ -87,7 +87,7 @@ 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.key = actions[0].get("id") result.status_code = 400 result.succeeded = False self.uploaded = self.uploaded + len(actions) - 1 @@ -109,7 +109,7 @@ def mock_fail_index_documents(actions, timeout=86400): if len(actions) > 0: result = IndexingResult() - result.key = actions[0].additional_properties.get("id") + result.key = actions[0].get("id") result.status_code = 400 result.succeeded = False self.uploaded = self.uploaded + len(actions) - 1 @@ -131,7 +131,7 @@ 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.key = actions[0].get("id") result.status_code = 200 result.succeeded = True return [result] 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 index c9d8c488d1ce..d45e331613a1 100644 --- a/sdk/search/azure-search-documents/tests/test_index_documents_batch.py +++ b/sdk/search/azure-search-documents/tests/test_index_documents_batch.py @@ -64,6 +64,3 @@ def test_add_method(self, method_name): 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_models.py b/sdk/search/azure-search-documents/tests/test_models.py index 299ee69091a6..13576881dda3 100644 --- a/sdk/search/azure-search-documents/tests/test_models.py +++ b/sdk/search/azure-search-documents/tests/test_models.py @@ -14,7 +14,7 @@ def test_encryption_key_serialization(): - from azure.search.documents.indexes._generated.models import ( + from azure.search.documents._generated.indexes.models import ( SearchResourceEncryptionKey as SearchResourceEncryptionKeyGen, ) diff --git a/sdk/search/azure-search-documents/tests/test_queries.py b/sdk/search/azure-search-documents/tests/test_queries.py index dacac2c74ad1..f343cbe159cf 100644 --- a/sdk/search/azure-search-documents/tests/test_queries.py +++ b/sdk/search/azure-search-documents/tests/test_queries.py @@ -68,9 +68,6 @@ 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 diff --git a/sdk/search/azure-search-documents/tests/test_regex_flags.py b/sdk/search/azure-search-documents/tests/test_regex_flags.py index cee471b5d1df..38db0e923d8b 100644 --- a/sdk/search/azure-search-documents/tests/test_regex_flags.py +++ b/sdk/search/azure-search-documents/tests/test_regex_flags.py @@ -9,7 +9,7 @@ PatternAnalyzer, PatternTokenizer, ) -from azure.search.documents.indexes._generated.models import ( +from azure.search.documents._generated.indexes.models import ( PatternAnalyzer as _PatternAnalyzer, PatternTokenizer as _PatternTokenizer, ) diff --git a/sdk/search/azure-search-documents/tests/test_search_client.py b/sdk/search/azure-search-documents/tests/test_search_client.py index f8833f55fdec..47df5fd52e9e 100644 --- a/sdk/search/azure-search-documents/tests/test_search_client.py +++ b/sdk/search/azure-search-documents/tests/test_search_client.py @@ -110,7 +110,7 @@ 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") + @mock.patch("azure.search.documents._generated.operations._operations.DocumentsOperations.count") def test_get_document_count(self, mock_count): client = SearchClient("endpoint", "index name", CREDENTIAL) client.get_document_count() @@ -119,7 +119,7 @@ def test_get_document_count(self, mock_count): 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") + @mock.patch("azure.search.documents._generated.operations._operations.DocumentsOperations.get") def test_get_document(self, mock_get): client = SearchClient("endpoint", "index name", CREDENTIAL) client.get_document("some_key") @@ -140,14 +140,14 @@ def test_get_document(self, mock_get): 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") + @mock.patch("azure.search.documents._generated.operations._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"})] + search_result.results = [SearchResult({"key": "val"})] mock_search_post.return_value = search_result assert not mock_search_post.called next(result) @@ -155,7 +155,7 @@ def test_search_query_argument(self, mock_search_post): 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") + @mock.patch("azure.search.documents._generated.operations._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") @@ -170,23 +170,21 @@ def test_suggest_bad_argument(self): 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") + @mock.patch("azure.search.documents._generated.operations._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"})] + search_result.results = [SearchResult({"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" - ) + @mock.patch("azure.search.documents._generated.operations._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") @@ -195,7 +193,7 @@ def test_autocomplete_query_argument(self, mock_autocomplete_post): 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") + @mock.patch("azure.search.documents._generated.operations._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() @@ -204,7 +202,7 @@ def test_get_document_count_v2020_06_30(self, mock_count): 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") + @mock.patch("azure.search.documents._generated.operations._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") @@ -225,14 +223,14 @@ def test_get_document_v2020_06_30(self, mock_get): 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") + @mock.patch("azure.search.documents._generated.operations._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"})] + search_result.results = [SearchResult({"key": "val"})] mock_search_post.return_value = search_result assert not mock_search_post.called next(result) @@ -240,7 +238,7 @@ def test_search_query_argument_v2020_06_30(self, mock_search_post): 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") + @mock.patch("azure.search.documents._generated.operations._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") @@ -249,9 +247,7 @@ def test_suggest_query_argument_v2020_06_30(self, mock_suggest_post): 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" - ) + @mock.patch("azure.search.documents._generated.operations._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") @@ -280,11 +276,10 @@ def test_add_method(self, arg, method_name): 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") + @mock.patch("azure.search.documents._generated.operations._operations.DocumentsOperations.index") def test_index_documents(self, mock_index): client = SearchClient("endpoint", "index name", CREDENTIAL) 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..31d0622a8891 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,14 @@ 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 len(results) == 1 + result = results[0] + assert result.text == "motel" + assert result.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"}, - ] + assert results[0].text == "Cheapest hotel in town. Infact, a motel." + assert results[0]["hotelId"] == "2" + assert results[1].text == "Secret Point Motel" + assert results[1]["hotelId"] == "9" 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 index 73973e36d3f1..661134667c5e 100644 --- a/sdk/search/azure-search-documents/tests/test_search_index_client.py +++ b/sdk/search/azure-search-documents/tests/test_search_index_client.py @@ -52,7 +52,7 @@ def test_get_search_client_inherit_api_version(self): 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" + "azure.search.documents._generated.indexes.operations._operations._SearchServiceClientOperationsMixin.get_service_statistics" ) def test_get_service_statistics(self, mock_get_stats): client = SearchIndexClient("endpoint", CREDENTIAL) @@ -62,7 +62,7 @@ def test_get_service_statistics(self, mock_get_stats): 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" + "azure.search.documents._generated.indexes.operations._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) 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..1742d6698103 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 result.keys() + assert "limits" in result.keys() def _test_list_indexes_empty(self, client): result = client.list_indexes() @@ -63,10 +63,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 result.document_count is not None + assert result.storage_size is not None + assert result.vector_index_size is not None def _test_create_index(self, client, index_name): fields = [ diff --git a/sdk/search/azure-search-documents/tests/test_serialization.py b/sdk/search/azure-search-documents/tests/test_serialization.py index 09a5f04caf32..be9f34ddbd53 100644 --- a/sdk/search/azure-search-documents/tests/test_serialization.py +++ b/sdk/search/azure-search-documents/tests/test_serialization.py @@ -47,12 +47,12 @@ def test_serialize_search_index(): ) search_index_serialized = index.serialize() search_index = SearchIndex.deserialize(search_index_serialized) - assert search_index + assert search_index is not None def test_serialize_search_indexer_skillset(): - COGNITIVE_KEY = ... - COGNITIVE_DESCRIPTION = ... + COGNITIVE_KEY = "KEY" + COGNITIVE_DESCRIPTION = "DESCRIPTION" cognitive_services_account = CognitiveServicesAccountKey(key=COGNITIVE_KEY, description=COGNITIVE_DESCRIPTION) @@ -76,7 +76,7 @@ def test_serialize_search_indexer_skillset(): serialized_skillset = skillset.serialize() skillset = SearchIndexerSkillset.deserialize(serialized_skillset) - assert skillset + assert skillset is not None def test_serialize_search_index_dict(): @@ -105,4 +105,4 @@ def test_serialize_search_index_dict(): ) search_index_serialized_dict = index.as_dict() search_index = SearchIndex.from_dict(search_index_serialized_dict) - assert search_index + assert search_index is not None